<template>
    <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :rules="rules" :model="allCityData" ref="allCityData" class="formInline" label-width="80px" slot="form">
                <!-- edit by cuihd at 2018/8/8 -->
                <!-- 将原“查询条件”的所属省、市区、区县删掉，这些查询条件区分度小，可能会查出几十万的数据 -->
                <!-- 直接使用区分度高的学校名称来查询，学校名称为必填项 -->
                <!-- <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="省份" prop="provinceId" >
                          <province v-model="allCityData.provinceId" @change="changeProvice"></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市区">
                          <city v-model="allCityData.cityId" :province="allCityData.provinceId" @change="changeCity"></city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区县">
                            <region v-model="allCityData.areaId" :city="allCityData.cityId" @change="changeArea"></region>
                        </el-form-item>
                    </el-col>
                  </el-row> -->
                  <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="学校名称" prop="getSchool">
                          <el-autocomplete v-model="allCityData.getSchool" :fetch-suggestions="remoteMethod" :trigger-on-focus="true" placeholder="请输入学校名称" @select="queryAllGrade" style="width:100%"></el-autocomplete>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班主任">
                            <el-select v-model="sUserName" placeholder="请下拉选择" style="width:100%;" :loading="loading">
                              <el-option v-for="item in ownerNameList" :key="item.fUserId" :label="item.sUserName" :value="item.sUserName">
                              </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班级编号">
                            <el-select v-model="classNum" placeholder="请选择查询的班级编号" style="width:100%;" :disabled="isClassNum" @change="classChange">
                              <el-option v-for="item in classList" :key="item" :label="item.sClassNum" :value="item.pId">
                              </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="41">  
                    <el-col :span="8">
                        <el-form-item label="年级" v-if="train">
                            <el-select v-model="getGradeName" placeholder="请选择查询的年级" style="width:100%;" @change="queryAllClass( getGradeName )">
                              <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId">
                              </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班级名称">
                            <el-autocomplete v-model="sNickName" :fetch-suggestions="queryAllClassName" :trigger-on-focus="true" placeholder="请输入查询的班级名称" @select="queryClassName" @change="nameChange" style="width:100%"></el-autocomplete>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="top-line">
                    <el-button type="primary" @click="onSubmit('allCityData')" native-type="button">查询</el-button>
                </div>
            </el-form>
            <div class="table-title" slot="table-title">
                <span class="table-title-span">
                  <el-button @click="addClass">添加班级</el-button>
                  <el-button @click="exportClass">班级导出</el-button>
                </span>
            </div>
            <el-table :data="dataApply" style="width: 100%" border v-loading="loading">
                <el-table-column label="学校名称" align="center" prop="schoolName" min-width="200px">
                  <template scope="scope">
                    {{!scope.row.schoolName ? '--' : scope.row.schoolName}}
                  </template>
                </el-table-column>
                <el-table-column label="班级编号" align="center" prop="classNum" >
                   <template scope="scope">
                    {{!scope.row.classNum ? '--' : scope.row.classNum}}
                  </template>
                </el-table-column>
                <el-table-column label="班级名称" align="center" prop="className">
                  <template scope="scope">
                    {{!scope.row.className ? '--' : scope.row.className}}
                  </template>
                </el-table-column>
                <el-table-column label="年级" align="center" prop="gradeName" >
                  <template scope="scope">
                    {{!scope.row.gradeName ? '--' : scope.row.gradeName}}
                  </template>
                </el-table-column>
                <el-table-column label="学生数量" align="center" prop="studentNumber" >
                  <template scope="scope">
                    <el-button type="text" class="btn-success" @click="btnStudentData(scope.row)">{{!scope.row.studentNumber ? '--' : scope.row.studentNumber}}</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="班主任" align="center" prop="ownerName" >
                  <template scope="scope">
                    {{!scope.row.ownerName ? '--' : scope.row.ownerName}}
                  </template>
                </el-table-column>
                
                <el-table-column label="班级码" align="center" prop="classCode" >
                  <template scope="scope">
                    {{!scope.row.classCode ? '--' : scope.row.classCode}}
                  </template>
                </el-table-column>
                <el-table-column label="其他操作" align="left" width="200">
                    <template scope="scope">
                      <el-button type="text" class="btn-success" @click="classDetails(scope.row)">班级详情</el-button>
                      <el-button type="text" class="btn-success" @click="delClass(scope.row)">删除</el-button>
                      <!-- 0禁用 1启用 -->
                      <el-button type="text" class="btn-success" @click="betProhibit(scope.row.classId,scope.row.status,scope.row)" v-cloak>{{scope.row.status == 1 ? '禁用' : '启用'}}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>

        <!-- 添加班级 -->
        <addClassSchool @addClassState="addClassState" v-if="addClassMain.dialogFormVisible" :addClassMain="addClassMain"></addClassSchool>
    </div>
</template>

<script>
import {
  getclassAll,
  classListData,
  deleteClass,
  getSchoolList,
  getGrade,
  getClass,
  getOwnerList,
  getClassName,
  groupChart
} from "api/classAll";
import TableLayout from "components/TableLayout";
import { mapState, mapActions, mapGetters } from "vuex";
import addClassSchool from "./addClassSchool";
import province from "components/CascadeRegion/province";
import city from "components/CascadeRegion/city";
import region from "components/CascadeRegion/region";
export default {
  name: "classAll",
  components: {
    TableLayout,
    // headmasterData,
    addClassSchool,
    province,
    city,
    region
  },
  data() {
    return {
      listQuery: {
        //分页
        page: 1,
        total: 0
      },

      //添加班级-子组件
      addClassMain: {
        dialogFormVisible: false,
        provinceId: ""
      },

      //查询所有数据集合
      formInline: {},
      loading: false,

      //table数组集合
      dataApply: [],

      //省市区三个集合
      allCity: {
        province: [],
        cityList: [],
        CountyList: []
      },

      //学校集合
      schoolList: [],

      //年级集合
      gradeList: [],

      //班级编辑集合
      classList: [],

      //班主任集合
      ownerNameList: [],

      //班级名称集合
      classNameArray: [],

      //省市区v-model数据
      allCityData: {
        provinceId: "",
        cityId: "",
        areaId: "",
        getSchool: "" //获取学校名称
      },

      //获取学校名称
      // getSchool: "",

      //获取班主任
      sUserName: "",

      //获取年级
      getGradeName: "",

      //获取班级编号
      classNum: "",

      //获取学校id
      newSchoolId: "",

      //班级名称
      sNickName: "",

      //判断班级编号是否为空
      isClassNum: false,

      //新的班级编号
      newClassNum: "",

      //判断是否是培训学校
      train: false,
      rules: {
        // provinceId: [{ required: true, message: "请输入省份" }], // edit by cuihd at 2018/8/8
        getSchool: [{required: true, message: '请先输入学校'}] // edit by cuihd at 2018/8/8
      }
    };
  },
  computed: {
    ...mapState({
      cacheUpdated: state => state.app.cacheUpdated, // 局部刷新列表
      config: state => state.config.table
    }),
    ...mapGetters(["uid", "token"])
  },
  //初始化
  created() {
    // this.searchFetchData();
  },
  watch: {
    // 局部刷新列表
    cacheUpdated(val) {
      val == 2 && this.searchFetchData();
    }
  },
  methods: {
    ...mapActions(["ChangePageSize"]),
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //分页
    handleSizeChange(val) {
      this.ChangePageSize(val);
      this.$refs.allCityData.validate(valid => {
        if (valid) {
          this.listQuery.page = 1;
          this.searchFetchData();
        }
      });
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.searchFetchData();
    },
    changeProvice() {
      this.allCityData.getSchool = "";
      this.newSchoolId = "";
      this.dataApply = [];
      this.listQuery.total = 0;
    },
    changeCity() {
      this.allCityData.getSchool = "";
      this.newSchoolId = "";
    },
    changeArea() {
      this.allCityData.getSchool = "";
      this.newSchoolId = "";
    },
    //模糊查询学校名称
    remoteMethod(query, cb) {
      if (this.allCityData.getSchool !== query && this.allCityData.getSchool !== "") {
        this.queryAllGrade("");
      }
      if (query) {
        getSchoolList(
          query,
          this.allCityData.provinceId,
          this.allCityData.cityId,
          this.allCityData.areaId
        )
          .then(response => {
            this.schoolList = response.data.content;
          })
          .then(() => {
            let results = this.schoolList.filter(this.createStateFilter(query));
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              // cb(results);
              if (results.length) {
                cb(results);
              } else {
                cb([{ value: "无数据" }]);
                this.$nextTick(() => {
                  let firstSelect = $(
                    ".el-autocomplete-suggestion__list li:nth-of-type(1)"
                  );
                  firstSelect.addClass("remoteMethodScy");
                });
              }
            }, 200 * Math.random());
          });
      } else {
        this.sNickName = "";
        this.classNum = "";
        this.classList = [];
        this.allCityData.getSchool = "";
        this.newSchoolId = "";
        this.getGradeName = "";
        this.gradeList = [];
        cb([]);
      }
      if (query !== "") {
        let getSchoolId = this.schoolList.forEach(item => {
          if (item.schoolName === query) return item.schoolId;
        });
      } else {
        this.allCityData.getSchool = "";
        this.sNickName = "";
        this.classNum = "";
        this.classList = [];
        this.ownerNameList = [];
        this.sUserName = "";
        this.newSchoolId = "";
        this.getGradeName = "";
        this.gradeList = [];
        cb([{ value: "无数据" }]);
        this.$nextTick(() => {
          let firstSelect = $(
            ".el-autocomplete-suggestion__list li:nth-of-type(1)"
          );
          firstSelect.addClass("remoteMethodScy");
        });
      }
    },
    createStateFilter(query) {
      return state => {
        state.value = state.schoolName;
        return state.value.toLowerCase().includes(query.toLowerCase());
      };
    },
    // 年级列表
    queryAllGrade(val) {
      if (!val.schoolId) {
        this.allCityData.getSchool = "";
        return false;
      } else {
        //设置学校id
        this.newSchoolId = val.schoolId;
        //班主任下拉
        getOwnerList(!val.schoolId ? null : val.schoolId).then(data => {
          this.ownerNameList = data.data.content;
          if (this.ownerNameList) {
            this.ownerNameList.unshift({
              fSchoolId: null,
              fUserId: null,
              pId: null,
              sCreateTime: null,
              sSchoolName: null,
              sUserName: "请选择"
            });
          }
        });
        //判断是否为培训学校  1 培训学校
        this.schoolList.forEach(item => {
          if (item.schoolId == val.schoolId) {
            if (item.schoolType == "1") {
              this.train = false;
              getClassName(item.schoolId).then(response => {
                this.classList = response.data.content;
              });
            } else {
              this.train = true;
              this.getGradeName = "";
              getGrade(!val.schoolId ? null : val.schoolId).then(response => {
                this.gradeList = response.data.content;
                this.newClassNum = "";
                this.gradeList.unshift({
                  gradeName: "请选择年级",
                  gradeId: ""
                });
              });
            }
          }
        });
      }
    },
    classChange(cid) {
      if (!cid) {
        return false;
      } else {
        //获取lable的值
        this.newClassNum = "";
        let obj = this.classList.find(item => {
          return item.pId === cid;
        });
        this.newClassNum = obj.sClassNum;
        this.classList.find(item => {
          if (cid === item.pId) {
            this.sNickName = item.sNickName;
          }
        });
      }
    },
    //下拉清除
    queryClassName(val) {
      if (!val.pId) {
        this.sNickName = "";
      }
    },
    nameChange(cid) {
      if (!cid) {
        this.sNickName = "";
      }
      if (this.getClassNum(cid)) {
        this.classNameArray.forEach(item => {
          if (cid === item.pId) {
            this.sNickName = item.sNickName;
          }
        });
      }
    },
    getGradeNameFn() {
      var gn = "";
      if (!this.gradeList) {
        return false;
      } else {
        this.gradeList.forEach(g => {
          if (g.gradeId == this.getGradeName) {
            gn = g.gradeName;
          }
        });
      }
      return gn;
    },
    getClassNum(cid) {
      var cn = "";
      if (!this.classList) {
        return false;
      } else {
        this.classList.forEach(c => {
          if (c.pId == cid) {
            cn = c.sClassNum;
          }
        });
      }
      return cn;
    },
    // 班级列表
    queryAllClass(gradeId) {
      if (gradeId) {
        // this.classIdIn = gradeId;
        this.classNum = "";
        this.sNickName = "";
        // this.sNickName = this.getGradeNameFn();
        getClassName(
          !this.newSchoolId ? null : this.newSchoolId,
          !gradeId ? null : gradeId
        ).then(data => {
          this.classList = data.data.content;
        });
      } else {
        this.newClassNum = "";
        this.classNum = "";
        this.sNickName = "";
        this.classList = [];
      }
    },
    //模糊查询班级名称
    queryAllClassName(query, cb) {
      if (query) {
        getClassName(
          !this.newSchoolId ? null : this.newSchoolId,
          !this.getGradeName ? null : this.getGradeName,
          !this.classNum ? null : this.classNum,
          !query ? null : query
        )
          .then(response => {
            this.classNameArray = response.data.content;
            // console.log(this.classNameArray)
          })
          .then(() => {
            if (!this.classNameArray) {
              cb([{ value: "无数据" }]);
              this.$nextTick(() => {
                let firstSelect = $(
                  ".el-autocomplete-suggestion__list li:first"
                );
                firstSelect.addClass("remoteMethodScy");
              });
              return false;
            }
            let results = this.classNameArray.filter(
              this.createClassFilter(query)
            );
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              if (results.length) {
                cb(results);
              } else {
                cb([{ value: "无数据" }]);
                this.$nextTick(() => {
                  let firstSelect = $(
                    ".el-autocomplete-suggestion__list li:first"
                  );
                  firstSelect.addClass("remoteMethodScy");
                });
              }
            }, 200 * Math.random());
          });
      } else {
        this.sNickName = "";
        cb([{ value: "无数据" }]);
        this.$nextTick(() => {
          let firstSelect = $(".el-autocomplete-suggestion__list li:first");
          firstSelect.addClass("remoteMethodScy");
        });
      }
    },
    createClassFilter(query) {
      return state => {
        state.value = state.sNickName;
        return state.value.toLowerCase().includes(query.toLowerCase());
      };
    },
    //查询列表
    searchFetchData() {
      this.loading = true;
      classListData(
        !this.allCityData.provinceId ? null : this.allCityData.provinceId,
        !this.allCityData.cityId ? null : this.allCityData.cityId,
        !this.allCityData.areaId ? null : this.allCityData.areaId,
        !this.newSchoolId ? null : this.newSchoolId,
        this.sUserName == "请选择" ? null : this.sUserName,
        !this.getGradeName ? null : this.getGradeName,
        !this.sNickName ? null : this.sNickName,
        // null,
        !this.newClassNum ? null : this.newClassNum,
        this.listQuery.page,
        this.config.pageSize
      )
        .then(response => {
          this.loading = false;
          if (!response.data.content) {
            this.dataApply = [];
            this.listQuery.total = 0;
          } else {
            this.dataApply = response.data.content.list;
            this.listQuery.total = response.data.content.pagination.total;
          }
        })
        .catch(error => {
          this.loading = false;
        });
    },
    //表单查询
    onSubmit(allCityData) {
      this.$refs[allCityData].validate(valid => {
        if (valid) {
          this.loading = true;
          this.listQuery.page = 1;
          if (this.allCityData.provinceId){
            this.addClassMain.provinceId = this.allCityData.provinceId;
          }
          // this.addClassMain.provinceId = this.allCityData.provinceId;
          this.searchFetchData();
        } else {
          return false;
        }
      });
    },
    addClass() {
      this.addClassMain.dialogFormVisible = true;
    },
    btnStudentData(val) {
      this.$router.push({ path: `studentList/${val.classId}` });
      // 整页刷新
      this.$store.dispatch("UpdateCache", true);
    },
    delClass(val) {
      //判断学生数量是否等于0
      if (val.studentNumber !== "0") {
        this.$message({
          // showClose: true,
          type: "info",
          message: "需要删除所有学生才能删除班级哦~"
        });
      } else {
        this.$confirm("确定删除该班级, 是否继续?", " ", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
          // type: "warning"
        })
          .then(() => {
            this.loading = true;
            deleteClass(val.classId)
              .then(data => {
                this.loading = false;
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.searchFetchData();
              })
              .catch(Error => {
                this.loading = false;
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },
    betProhibit(val, sta, num) {
      //判断学生数量是否为空
      if (num.studentNumber > 0) {
        if (sta == 0) {
          this.$confirm("是否启用群聊?", " ", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: " "
          })
            .then(() => {
              groupChart(val, 1).then(data => {
                this.$message({
                  message: "设置成功",
                  type: "success"
                });
                this.searchFetchData();
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        } else {
          this.$confirm("是否禁用群聊?", " ", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: " "
          })
            .then(() => {
              groupChart(val, 0).then(data => {
                this.$message({
                  message: "设置成功",
                  type: "success"
                });
                this.searchFetchData();
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        }
      } else {
        this.$message({
          message: "该班级目前不支持群聊",
          type: "warning"
        });
      }
    },
    addClassState(val) {
      if (!val) {
      } else {
        //从新发送请求
        this.sUserName = "";
        this.getGradeName = "";
        this.sNickName = "";
        this.newClassNum = "";
        if (!this.allCityData.provinceId) {
        } else {
          this.listQuery.page = 1;
          this.searchFetchData();
        }
      }
    },
    //班级详情跳转
    classDetails(val) {
      this.$router.push({ path: `classDetails/${val.classId}` });
      // 整页刷新
      this.$store.dispatch("UpdateCache", true);
    },
    //导出
    exportClass() {
      let sUserName = this.sUserName == "请选择" ? null : this.sUserName;
      if (this.listQuery.total !== 0) {
        window.location.href = `${
          LOCAL_API.ly
        }/class/exportClassByCondition?provinceId=${
          this.allCityData.provinceId
        }&cityId=${this.allCityData.cityId}&areaId=${
          this.allCityData.areaId
        }&schoolId=${this.newSchoolId}&ownerName=${sUserName}&grade=${
          this.getGradeName
        }&className=${this.sNickName}&classNum=${this.newClassNum}&token=${
          this.token
        }`;
      } else {
        this.$message("目前没有数据哦~~");
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.content {
  position: relative;
  padding: 0px;
  $bgcolor: #fff;
  .formInline {
    .formBtn {
      width: 100%;
      height: 70px;
      border-top: 1px solid #dddddd;
      position: relative;
    }
  }
}
</style>